//
//  CALUtilityTools.m
//  CheckAutoBaseCoreLib
//
//  Created by 孙威 on 15/12/16.
//  Copyright © 2015年 youxinpai. All rights reserved.
//

#import "CALUtilityTools.h"
#import <AFNetworking.h>
#import <MBProgressHUD.h>
#import <sys/sysctl.h>
#import <ImageIO/ImageIO.h>
#import <AVFoundation/AVFoundation.h>
#import <mach/mach.h>
#import <sys/sysctl.h>

@implementation CALUtilityTools

+ (NSString *)replaceUnicode:(NSString *)unicodeStr
{
    
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u"withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""];
    NSString *tempStr3 = [[@"\""stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];
}

+ (void)showTips:(NSString *)tips forSecond:(CGFloat)second onView:(UIView *)view
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].windows objectAtIndex:0] animated:YES];
    
    // Configure for text only and offset down
    hud.mode = MBProgressHUDModeText;
    hud.labelText = tips;
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hide:YES afterDelay:second];
    
}

/* 生成缩略图 */
+ (UIImage *)getThumbFromImage:(UIImage *)oldImage scaleFactor:(CGFloat)factor
{
    UIGraphicsBeginImageContext(CGSizeMake(oldImage.size.width * factor, oldImage.size.height * factor));
    
    [oldImage drawInRect:CGRectMake(0.0, 0.0, oldImage.size.width * factor, oldImage.size.height * factor)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

+ (NSString *)getDocumentPathFromFilePath:(NSString *)filePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    
    return [NSString stringWithFormat:@"%@/%@", docDir, filePath];
}

+ (NSString *)cacheImage:(NSData *)imageData atDic:(NSString *)imageDic withName:(NSString *)imageName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    
    NSString *carImageDicPath = [NSString stringWithFormat:@"%@/%@", docDir, imageDic];
    NSError *error;
    
    BOOL isDic;
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:carImageDicPath isDirectory:&isDic]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:carImageDicPath withIntermediateDirectories:YES attributes:nil error:&error];
    }
    
    NSString *fullPath = [carImageDicPath stringByAppendingPathComponent:imageName];
    [imageData writeToFile:fullPath atomically:YES];
    
    NSString *filePath = [NSString stringWithFormat:@"/carImages/%@/%@", imageDic, imageName];
    
    return filePath;
}

+ (NSString *)getCurrentTimeWithFormat:(NSString *)format
{
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    [dateFormatter setDateFormat:format];
    NSString *dateTime = [dateFormatter stringFromDate:[NSDate date]];
    
    return dateTime;
}

+ (BOOL)isNotEmptyString:(NSString *)text
{
    if (![text isKindOfClass:[NSString class]]) {
        return NO;
    }
    
    if (!text || [text isEqualToString:@""]) {
        return NO;
    }
    
    return YES;
}

+ (long long)fileSizeAtPath:(NSString*) filePath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    
    return 0;
}

+ (CGFloat)fileSizeForDir:(NSString*)folderPath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath])
        return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil)
    {
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    
    return folderSize/(1024.0*1024.0);
}

+ (BOOL)clearCacheAtPath:(NSString *)filePath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSError *error;
    [manager removeItemAtPath:filePath error:&error];
    
    if (!error) {
        return YES;
    }else {
        return NO;
    }
}

+ (NSString *)getCurrentDeviceModel
{
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G (A1203)";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G (A1241/A1324)";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS (A1303/A1325)";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (A1349)";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S (A1387/A1431)";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (A1428)";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (A1429/A1442)";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (A1456/A1532)";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (A1507/A1516/A1526/A1529)";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (A1453/A1533)";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (A1457/A1518/A1528/A1530)";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
    
    
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";

    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G (A1213)";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G (A1288)";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G (A1318)";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G (A1367)";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G (A1421/A1509)";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G (A1219/A1337)";
    
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2 (A1395)";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2 (A1396)";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2 (A1397)";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2 (A1395+New Chip)";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G (A1432)";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G (A1454)";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G (A1455)";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3 (A1416)";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3 (A1403)";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3 (A1430)";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4 (A1458)";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4 (A1459)";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4 (A1460)";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air (A1474)";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air (A1475)";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air (A1476)";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G (A1489)";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G (A1490)";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G (A1491)";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    return platform;
}

+ (NSString *)getCurrentDeviceType
{
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"2";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"3";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"3";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"4";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"4";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"4";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"4";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"5";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"5";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"5";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"5";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"5";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"5";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"6+";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"6";
    
    if ([platform isEqualToString:@"iPhone8,1"]) return @"6s";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"6s+";
    
    
    
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G (A1213)";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G (A1288)";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G (A1318)";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G (A1367)";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G (A1421/A1509)";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G (A1219/A1337)";
    
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2 (A1395)";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2 (A1396)";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2 (A1397)";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2 (A1395+New Chip)";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G (A1432)";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G (A1454)";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G (A1455)";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3 (A1416)";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3 (A1403)";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3 (A1430)";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4 (A1458)";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4 (A1459)";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4 (A1460)";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air (A1474)";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air (A1475)";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air (A1476)";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G (A1489)";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G (A1490)";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G (A1491)";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    return platform;
}

+ (NSData *)bindImageData:(NSData*)jpeg withMetaDataDictionary:(NSDictionary*)dicRef
{
    CGImageSourceRef source =CGImageSourceCreateWithData((__bridge CFDataRef)jpeg, NULL);
    NSDictionary *dict = (__bridge_transfer NSDictionary*)CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
    
    NSMutableDictionary *metaDataDic = [dict mutableCopy];
    
    NSMutableDictionary *exifDic =[[metaDataDic objectForKey:(NSString*)kCGImagePropertyExifDictionary]mutableCopy];
    NSMutableDictionary *tiffDic = [NSMutableDictionary dictionary];
    if(!exifDic)
    {
        exifDic = [NSMutableDictionary dictionary];
    }
    
    NSString *deviceModel = [self getCurrentDeviceModel];
    [tiffDic setObject:@"Apple" forKey:(NSString *)kCGImagePropertyTIFFMake];
    [tiffDic setObject:deviceModel forKey:(NSString *)kCGImagePropertyTIFFModel];
    [metaDataDic setObject:exifDic forKey:(NSString*)kCGImagePropertyExifDictionary];
    [metaDataDic setObject:tiffDic forKey:(NSString *)kCGImagePropertyTIFFDictionary];
    
    //    source = CGImageSourceCreateWithData((__bridge CFDataRef)jpeg, NULL);
    
    CFStringRef UTI = CGImageSourceGetType(source);
    
    NSMutableData *dest_data = [NSMutableData data];
    
    CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)dest_data,UTI,1,NULL);
    
    CGImageDestinationAddImageFromSource(destination,source,0, (__bridge CFDictionaryRef) metaDataDic);
    
    CFRelease(source);
    BOOL success = NO;
    success = CGImageDestinationFinalize(destination);
    
    if(!success) {
        NSLog(@"***Could not create data from image destination ***");
    }
    
    CFRelease(destination);
    //    CFRelease(source);
    
    return dest_data;
}

+ (void)updateApp
{
    NSURL *url = [NSURL URLWithString:@"itms-services://?action=download-manifest&url=https://app.youxinpai.com/CheckAutoiOS/chake.plist"];
    [[UIApplication sharedApplication] openURL:url];
    
    exit(0);
}

+ (void)monitorNetworkStatus
{
    /* 网络状态监听 */
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        //        NSString *netStatusMessage = nil;
        
        //        switch (status) {
        //            case AFNetworkReachabilityStatusNotReachable:
        //                netStatusMessage = @"网络断开";
        //                break;
        //            case AFNetworkReachabilityStatusReachableViaWiFi:
        //                netStatusMessage = @"通过Wi-Fi连接网络";
        //                break;
        //            case AFNetworkReachabilityStatusReachableViaWWAN:
        //                netStatusMessage = @"通过移动网络连接";
        //                break;
        //            case AFNetworkReachabilityStatusUnknown:
        //                netStatusMessage = @"网络状态异常";
        //                break;
        //
        //            default:
        //                break;
        //        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:CAL_NOTIFICATION_NETWORK_STATUS_CHANGED object:self userInfo:@{@"status": @(status)}];
    }];
}

+ (BOOL)isFileExistForPath:(NSString *)path isDirectory:(BOOL) isDirectory
{
    return [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDirectory];
}

+ (BOOL)createEmptyFileAtPath:(NSString *)filePath isDirectory:(BOOL)isDirectory withAttributes:(NSDictionary *) attributes
{
    BOOL isCreatedSucceed;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    isCreatedSucceed = isDirectory ? [fileManager createDirectoryAtPath:filePath
                                            withIntermediateDirectories:NO
                                                             attributes:attributes
                                                                  error:nil]
    : [fileManager createFileAtPath:filePath
                           contents:nil
                         attributes:attributes];
    
    return isCreatedSucceed;
    
}

+ (BOOL)deleteFileAtPath:(NSString *) filePath
{
    return [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}

+ (NSString *)cacheRootPath
{
    NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [pathList  objectAtIndex:0];
}

+ (NSString *)docRootPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

+ (id)getNSNullFromNilIfNecessary:(NSString *)string
{
    if (!string) {
        return [NSNull new];
    }else {
        return string;
    }
}

+ (void)requestCameraAccess
{
    NSString *mediaType = AVMediaTypeVideo;
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                ;
            } else {
                ;
            }
        }];
    }
}

+ (UIImage *)imageCompressForSizeImage:(UIImage *)image targetSize:(CGSize)size
{
    UIImage * newImage = nil;
    CGSize iamgeSize = image.size;
    CGFloat width = iamgeSize.width;
    CGFloat height  = iamgeSize.height;
    CGFloat targetWidth = size.width;
    CGFloat targetHeight = size.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaleWidth = targetWidth;
    CGFloat scaleHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if (CGSizeEqualToSize(iamgeSize, size)==NO)
    {
        CGFloat widthFactor = targetWidth/width;
        CGFloat heightFactor = targetHeight/height;
        if (widthFactor >heightFactor)
        {
            scaleFactor = widthFactor;
            
        }
        else
        {
            scaleFactor = heightFactor;
            
        }
        scaleWidth  =width * scaleFactor;
        scaleHeight = height * scaleFactor;
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight-scaleHeight)*0.5;
            
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth -scaleWidth)*0.5;
            
        }
        
    }
    UIGraphicsBeginImageContext(size);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaleWidth;
    thumbnailRect.size.height = scaleHeight;
    [image drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if (newImage==nil)
    {
        NSLog(@"scale image file");
    }
    UIGraphicsEndImageContext();
    
    
    return newImage;
}

+ (BOOL)haveEnoughSpace:(CGFloat)size
{
    NSDictionary *fsAttr = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    float diskFreeSize = [fsAttr[NSFileSystemFreeSize] doubleValue] / (1024*1024);
    
    if (diskFreeSize <= size) {
        return NO;
    } else {
        return YES;
    }
}

+ (double)usedMemory
{
    task_basic_info_data_t taskInfo;
    mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;
    kern_return_t kernReturn = task_info(mach_task_self(),
                                         TASK_BASIC_INFO,
                                         (task_info_t)&taskInfo,
                                         &infoCount);
    
    if (kernReturn != KERN_SUCCESS
        ) {
        return NSNotFound;
    }
    
    return taskInfo.resident_size / 1024.0 / 1024.0;
}

+ (NSString *)getCurrentTimeInterval
{
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
    
    return [NSString stringWithFormat:@"%.0f", interval];
}

+ (CGFloat)autoValueLittle:(CGFloat)little middle:(CGFloat)middle large:(CGFloat)large
{
    NSInteger screenWidth = MIN([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    
    switch (screenWidth) {
        case 320:
            return little;
            
        case 375:
            return middle;
            
        case 414:
            return large;
            
        default:
            return large;
    }
}

@end
